package com.ncs.cns.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ncs.cns.R;
import com.ncs.cns.business.constants.BundleConstants;
import com.ncs.cns.business.service.MessageService;
import com.ncs.cns.business.to.Message;
import com.ncs.cns.business.util.DateUtil;
import com.ncs.cns.framework.chat.ChattingClient;

public class CircuSeeChatActivity extends Activity {
	private ChattingClient client;
	private ListView chatListView;
	private Context context;
	private ChatAdapter chatAdapter;
	private ChatHandler handler;
	private int maxConnectTime = 2;//最大重试连接次数
	private int currentConnectTime = 1;//当前连接次数
	private ProgressBar bar;
	private TextView progressText;
	private int currentEventId;
	private TextView sendBtn;
	private String currentMsgId;
	private Boolean isLoadMsg = true;
	private MessageService msgService;
	private List<Message> messages = new ArrayList<Message>();
	private Message lastMessage = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_circu_see_chat);
		connectChatServer();
		init();
		loadMsgFromBD();
		sendBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {				
				EditText msgEt = (EditText) findViewById(R.id.sendMsgCotent);
				final String msg = msgEt.getText().toString();
				if(msg.trim().equals("") || client == null)return;
				notFastDoubleClick();
				currentMsgId = System.currentTimeMillis()+"";
				String now = DateUtil.formatDate(new Date(),DateUtil.yyyy_MM_dd_HH_mm_ss);
				final Message message = new Message(currentMsgId,msg,currentEventId+"","P",now,now);				
				lastMessage = message;
				messages.add(message);
				chatAdapter.notifyDataSetChanged();
				new Thread(){
					public void run() {
						try {							
							client.receieveFromUser(message);
						} catch (IOException e) {
							e.printStackTrace();
						}
					};
				}.start();
				msgEt.setText("");
			    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
			    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			    scrollListToBottom();
			}
		});
	}

	private void loadMsgFromBD() {
		messages = msgService.findMsgByEventId(currentEventId+"");
		chatAdapter.notifyDataSetChanged();
		if(messages.size() > 0){
			lastMessage  = messages.get(messages.size()-1);
		}
		Thread loadMsg = new Thread(new LoadMsgThread());
		loadMsg.start();
	}

	public void init(){
		context = this.getApplicationContext();		
		chatListView = (ListView) this.findViewById(R.id.chatList);
		chatAdapter = new ChatAdapter();
		chatListView.setAdapter(chatAdapter);
		handler = new ChatHandler();
		bar = (ProgressBar) this.findViewById(R.id.connectProgressBar);
		progressText = (TextView) this.findViewById(R.id.text_chat_connection);
		currentEventId = this.getIntent().getIntExtra(BundleConstants.BUNDLE_EVENT_ID, 0);
		sendBtn = (TextView) this.findViewById(R.id.sendMsgBtn);
		msgService = new MessageService(context);
	}
	public void notFastDoubleClick() {  
		  new Thread(){
			  @Override
			public void run() {
				super.run();
				sendBtn.setClickable(false);
				try {
					Thread.currentThread().sleep(1000);
				} catch (InterruptedException e) {
					sendBtn.setClickable(true);
				}
				sendBtn.setClickable(true);
			}
		  }.start();
	  }  
	
	public void scrollListToBottom(){
		int bottom = chatListView.getCount()-1;
		chatListView.setSelection(bottom);
	}
	
	public void connectChatServer(){
		SocketTask chatTask = new SocketTask();
		chatTask.execute();				
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	        isLoadMsg = false;	
//		 	if(client!=null){
//        		new Thread(){
//        			@Override
//        			public void run() {
//    	        		client.closeConnection();
//        			}
//        		}.start();
//        	}
    		finish();
    		return true;
        }	        
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.circu_see_chat, menu);
		return true;
	}
	
	
	class SocketTask extends AsyncTask<Void, Void, Boolean> {
          @Override
          protected Boolean doInBackground(Void... arg0) {
        	 boolean flag = false; 
             client = ChattingClient.getInstance(context);        
             if(client != null)flag = true;
             return flag;
          } 
          
          @Override
        protected void onPostExecute(Boolean result) {
        	super.onPostExecute(result);
        	if(currentConnectTime < maxConnectTime){
	        	if(!result){        	        		
	        		connectChatServer();
	        		currentConnectTime++;
	        	}
	        	else{
	        		bar.setVisibility(View.INVISIBLE);
	        		progressText.setVisibility(View.INVISIBLE);
	        	}
        	}else{
        		bar.setVisibility(View.INVISIBLE);
        		progressText.setText("未连接");
        	}
        	
        }
     }
	
	class LoadMsgThread implements Runnable{		
		@Override
		public void run() {
			while(isLoadMsg){
				try {
					Thread.currentThread().sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if(lastMessage == null || msgService.isNeedRefresh(lastMessage.getMessageId(), currentEventId+"")){
					List<Message> newMessages = msgService.getNewMessage(messages.size(), currentEventId+"");
					messages.addAll(newMessages);
					handler.sendMessage(new android.os.Message());
				}
			}
		}
	}
	
	class ChatHandler extends Handler{
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			chatAdapter.notifyDataSetChanged();
			scrollListToBottom();
		}
	}
	
	class ChatAdapter extends BaseAdapter{
		private LayoutInflater inflater;
		public ChatAdapter() {
			inflater = LayoutInflater.from(context);
		}
		@Override
		public int getCount() {
			return messages.size();
		}

		@Override
		public Object getItem(int location) {
			return messages.get(location);
		}

		@Override
		public long getItemId(int index) {
			return index;
		}

		@Override
		public View getView(int index, View contentView, ViewGroup parent) {
			View view;
			TextView tv = null;
			if(contentView == null){
				view = inflater.inflate(R.layout.chat_list_item, null, false);
				tv = (TextView) view.findViewById(R.id.chatListItem);
				view.setTag(tv);
			}
			else{
				view = contentView;		
				tv = (TextView) view.getTag();
			}
			tv.setText(messages.get(index).getContent());
			return view;
		}
	}
}
